import axios from 'axios'

const apiClient = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器
apiClient.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('access_token')
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 响应拦截器优化
apiClient.interceptors.response.use(
    (response) => {
        return response
    },
    (error) => {
        if (error.response?.status === 401) {
            // 只有在特定页面才跳转到登录页
            const currentPath = window.location.pathname
            const isAuthPage = currentPath.includes('/login')

            if (!isAuthPage) {
                localStorage.removeItem('access_token')
                // 显示提示信息
                alert('登录已过期，请重新登录')
                window.location.href = '/login'
            }
        }
        return Promise.reject(error)
    }
)

export default apiClient